package com.situ.mall.controller;

import com.situ.mall.pojo.Category;
import com.situ.mall.service.impl.CategoryServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @ClassName IndexController
 * @Description 负责一些页面的跳转
 * @Author 周轩霆
 * @Date 2022/8/16 16:06
 **/
@Controller
public class IndexController {
    //日志相关
    private Logger logger = LoggerFactory.getLogger(IndexController.class);
    @Autowired
    private CategoryServiceImpl categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/")
    public String index(Model model) {
        List<Category> topCategoryList = redisTemplate.opsForList().range("topCategoryList", 0, -1);
        //先判断有没有
        if (CollectionUtils.isEmpty(topCategoryList)) {
            //没有的话先查数据库 再保存到Redis中，下次直接返回
            topCategoryList = categoryService.selectTopCategoryList();
            redisTemplate.opsForList().rightPushAll("topCategoryList", topCategoryList);
        }

        List<Category> secondCategoryList = redisTemplate.opsForList().range("secondCategoryList", 0, -1);
        //先判断有没有
        if (CollectionUtils.isEmpty(secondCategoryList)) {
            //没有就查数据库
            secondCategoryList = categoryService.selectSecondCategoryList();
            redisTemplate.opsForList().rightPushAll("secondCategoryList", secondCategoryList);
        }
        model.addAttribute("topCategoryList", topCategoryList);
        model.addAttribute("secondCategoryList", secondCategoryList);
        return "index";
    }

    @RequestMapping("/login")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/logout")
    public String toLoginOut(HttpSession session) {
        //注销后 session失效 跳转页面
        session.invalidate();
        return "login";
    }

    @RequestMapping("toEcharts")
    public String toEcharts() {
        return "echarts";
    }

    @RequestMapping("/log")
    @ResponseBody
    public String log() {
        logger.debug("debug:hello");
        logger.info("info:info");
        logger.warn("warn:info");
        logger.error("debug:error");
        return "log!!!!";
    }
}
